# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# CM15a additionnal functions
# Python version 2.7.x and 3.x
# ----------------------------------------------------------------------------
# Software MOCHAD
# ---------------
# - Website: http://sourceforge.net/apps/mediawiki/mochad/index.php?title=Main_Page
# - MOCHAD is used as base for development of scripts
#
# Software CM15ademo
# ---------------
# - Website: http://www.eclipsehomeauto.com/
# - CM15ademo is used as base for development of scripts
# ----------------------------------------------------------------------------


import logging

logger = logging.getLogger()

RequestCmd = {
   'STAT':([0x8B],None,16,'Controller status'),
   'TEST':([0x04,0x66],0x55,1,'Test write House Code A'),
   }


def ackpwfail(dev):
    """
    After a powerfail, CM15 send Powerfail Signal / Request Set Time 0xA5
    Ack with the signal Timer Download  header 0x9B
    """
    import cm1xclock as clock
    logger.debug("Ack Powerfail Signal 0xA5.....")
    a = clock.clockbuf()
    logger.debug("Setclock buffer %s",repr(a))
    if dev.write(a):
        return True
    return False


def requestcmd(dev,rcmd):
    if rcmd in RequestCmd:
        seq, ack, lenresp, msg = RequestCmd[rcmd]
        logger.debug("Request %s to controller...",msg)
        r = dev.write(seq,ack)
        if r:
            logger.debug("Ack %s - Read %s",repr(ack),repr(r))
        if lenresp > 1:
            res = dev.read()
            return res
        return r
    return None


def testwrite(dev):
    logger.debug("Test writing 0x04 0x66 to controller")
    res = dev.write([0x04,0x66],0x55)
    if res:
        return res
    else:
        logger.critical("Unable to test CM15a, no response from CM15a")
        return None
